<?php
declare (strict_types = 1);

namespace app\frontend\middleware;

use app\backend\model\AdminMenu;
use app\backend\model\AdminRole;

class Permission
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        // 登录检验
        $adminInfo = session('adminInfo');
        if (empty($adminInfo)) {
            header('Location: /admin/login');
            exit;
        }
        // 非admin超级管理员才需要判断角色和权限
        if ($adminInfo['id'] != 1) {
            // 获取用户访问的控制器名称、方法名称
            $controller = request()->controller();
            $action = request()->action();
            $menu = AdminMenu::where([
                'controller' => $controller,
                'action' => $action
            ])->find();
            if (empty($menu)) {
                $this->outputErrorMsg('菜单不存在');
            }
            // 判断该用户是否被分配角色，分配的角色是否存在
            $role = AdminRole::where('id', $adminInfo['admin_role_id'])->find();
            if (empty($role)) {
                $this->outputErrorMsg('该角色不存在');
            }
            // 判断当前用户所属角色是否具有当前菜单的访问权限
            if (empty($role['menu_ids'])) {
                $this->outputErrorMsg('该角色没有被授权');
            }
            $menuIds = explode(',', $role['menu_ids']);
            if (!in_array($menu['id'], $menuIds)) {
                $this->outputErrorMsg('没有权限');
            }
        }

        return $next($request);
    }

    /**
     * 输出错误信息
     * @param string $msg 错误信息
     */
    private function outputErrorMsg($msg)
    {
        //重定向到错误页面
        if (request()->isAjax()) {
            exit(json_encode(['code'=>302, 'msg' => $msg]));
        } else {
            header('Location: /backend/error/' . $msg);
            exit;
        }
    }
}
